﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RentHouse.Service;
using RentHouse.Common;
using RentHouse.DTO;
using RentHouse.IService;
using RentHouse.Service.Entities;

namespace RentHouse.Service
{
    public class AdminUserService : IAdminUserService
    {
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="adminUserAdd"></param>
        /// <returns></returns>
        public AjaxResult Add(AdminUserAddDTO adminUserAdd)
        {
            using (var db = new RentHouseContext())
            {
                var admin = new BaseService<T_AdminUsers>(db);
                var role = new BaseService<T_Roles>(db);
                T_AdminUsers t_Admin = new T_AdminUsers
                {
                    CityId = adminUserAdd.CityId,
                    PasswordSalt = CommonHelper.CreateVerifyCode(5),
                    PasswordHash = CommonHelper.CalcMD5(adminUserAdd.Password + CommonHelper.CreateVerifyCode(5)),
                    CreateDateTime =DateTime.Now,
                    Email=adminUserAdd.Email,
                    Name=adminUserAdd.Name,
                    IsDeleted=false,
                    PhoneNum=adminUserAdd.PhoneNum,
                };
                foreach (var item in adminUserAdd.RoleIds)
                {
                    T_Roles t_Permissions = role.Get(e => e.Id == item);
                    t_Admin.T_Roles.Add(t_Permissions);
                }
                if (admin.Add(t_Admin) > 0)
                {
                    return new AjaxResult(ResultState.Success, "添加成功");
                }
                else
                {
                    return new AjaxResult(ResultState.Error, "添加失败");

                }
            }
        }
        
        /// <summary>
        /// 用户列表的展示
        /// </summary>
        /// <param name="length"></param>
        /// <param name="start"></param>
        /// <param name="name"></param>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        public List<AdminUserDTO> GetList(int length, int start, string name, ref int rowCount)
        {
            using (var model = new RentHouseContext())
            {
                var db = new BaseService<T_AdminUsers>(model);
                var query = PredicateExtensions.True<T_AdminUsers>();
                if (!string.IsNullOrWhiteSpace(name))
                {
                    query = query.And(e => e.Name.Contains(name));
                }
                var list = db.GetPagedList(start, length, ref rowCount, query, e => e.Id, false).Select(e => new AdminUserDTO
                {
                    Id = e.Id,
                    Name = e.Name,
                    CityId=e.CityId,
                    CityName=e.T_Cities.Name,
                     Email=e.Email,
                     PhoneNum=e.PhoneNum,
                     LoginErrorTimes=e.LoginErrorTimes
                }).ToList();
                return list;

            }
        }

        /// <summary>
        /// 单个删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AjaxResult Delete(long id)
        {
            using (var db = new RentHouseContext())
            {
                var service = new BaseService<T_AdminUsers>(db);
                var result = service.Get(e => e.Id == id);
                service.Delete(result);
                if (db.SaveChanges() > 0)
                    return new AjaxResult(ResultState.Success, "删除成功");
                else
                    return new AjaxResult(ResultState.Success, "删除失败");

            }
        }
        
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AjaxResult Deletes(long[] id)
        {
            try
            {
                foreach (var item in id)
                {
                    Delete(item);
                }
                return new AjaxResult(ResultState.Success, "删除成功");

            }
            catch (Exception)
            {
                return new AjaxResult(ResultState.Success, "删除失败");

            }

        }

        /// <summary>
        /// 根据用户Id查询该用户所对应的角色，在通过该用户角色查找对应角色所拥有的所有权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<PermissionDTO> GetPermissionsById(long id)
        {
            using (var db = new RentHouseContext())
            {
                var bs = new BaseService<T_AdminUsers>(db);
                List<PermissionDTO> permissions = new List<PermissionDTO>();
                var user = bs.Get(e => e.Id == id);
                foreach (var role in user.T_Roles)
                {
                   var permission=  role.T_Permissions.Select(t => new PermissionDTO()
                    {
                        Name=t.Name
                    }).ToList();
                    permissions.AddRange(permission);
                }
                return permissions;

            }

        }

    }
}
